微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

角度应用程序中的请求返回状态400

如何解决角度应用程序中的请求返回状态400

我正在尝试向asp.net核心后端发送发布请求,以验证输入名称,但收到状态为400错误的请求。

这是控制器:

import os
import time

#####################################################################################################
############################################Main Menu################################################
#####################################################################################################
def menu():
    os.system("cls")
    print("*"*20)
    print("Choose a command:")
    print("s = shutdown")
    print("r = restart")
    print("l = log off")
    print("h = hibernate")
    print("c = cancel command")
    print("q = quit")
    print("*"*20)
    commandtype = input(":")
    #opening command menus
    if commandtype in ["s","r","l","h","c","q","S","R","L","H","C","Q"]:
        pass
    else:
        menu()
    if commandtype in ["s","S"]:
        shutdownmenu()
    if commandtype in ["r","R"]:
        restartmenu()
    if commandtype in ["l","L"]:
        logoffmenu()
    if commandtype in ["h","H"]:
        hibernatemenu()
    if commandtype in ["c","C"]:
        try:
            os.system("cls")
            os.system("shutdown.exe /a")
            time.sleep(1)
        except:
            pass
        finally:
            os.system("cls")
            print("*"*10)
            print("   Done")
            print("*"*10)
            time.sleep(2)
            menu()
    if commandtype in ["q","Q"]:
        exit()

#####################################################################################################
############################################Shutdown Menu############################################
#####################################################################################################
def shutdownmenu():
    os.system("cls")
    print("*"*20)
    print("Shutdown time:")
    print("s = seconds")
    print("m = minutes")
    print("h = hours")
    print("b = back")
    print("q = quit")
    print("*"*20)
    timetype = input(":")
    #opening almenus
    if timetype in ["b","s","m","B","M","Q"]:
        pass
    else:
        shutdownmenu()
    if timetype in ["s","S"]:
        shutdownsecondsmenu()
    if timetype in ["m","M"]:
        shutdownminutesmenu()
    if timetype in ["h","H"]:
        shutdownhoursmenu()
    if timetype in ["b","B"]:
        menu()
    if timetype in ["q","Q"]:
        exit()

#Seconds Menu
def shutdownsecondsmenu():
    os.system("cls")
    print("*"*20)
    print("How many seconds?")
    print("0-60 seconds")
    print("b = back")
    print("q = quit")
    print("*"*20)
    second = input(":")
    #Menu key fuctions
    if second in ["b","Q"] or second in ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60"]:
        pass
    else:
        shutdownsecondsmenu()
    if second in ["b","B"]:
        shutdownmenu()
    if second in ["q","Q"]:
        exit()
    if second >= "0":
        #Shutdown with time
        os.system("shutdown.exe /s /t " + second)

#Minutes Menu
def shutdownminutesmenu():
    os.system("cls")
    print("*"*20)
    print("How many minutes?")
    print("(Just numbers!)")
    print("b = back")
    print("q = quit")
    print("*"*20)
    minutes = input(":")
    #Menu key fuctions
    if minutes in ["b","Q"] or "1" <= minutes:
        pass
    else:
        shutdownmenu()
    if minutes in ["b","B"]:
        shutdownmenu()
    if minutes in ["q","Q"]:
        exit()
    if minutes >= "1":
        #Minutes Calculation
        minsec = str(int(eval(minutes) * 60))
        #Shutdown with time
        os.system("shutdown.exe /s /t " + minsec)

#Hours Menu
def shutdownhoursmenu():
    os.system("cls")
    print("*"*20)
    print("How many hours?")
    print("(Just numbers!)")
    print("b = back")
    print("q = quit")
    print("*"*20)
    hours = input(":")
    #Menu key fuctions
    if hours in ["b","Q"] or "1" <= hours:
        pass
    else:
        shutdownhoursmenu()
    if hours in ["b","B"]:
        shutdownmenu()
    if hours in ["q","Q"]:
        exit()
    if hours >= "1":
        #Minutes Calculation
        hoursec = str(int(eval(hours) * 3600))
        #Shutdown with time
        os.system("shutdown.exe /s /t " + hoursec)

#####################################################################################################
############################################Restart Menu#############################################
#####################################################################################################
def restartmenu():
    os.system("cls")
    print("*"*20)
    print("Restart time:")
    print("s = seconds")
    print("m = minutes")
    print("h = hours")
    print("b = back")
    print("q = quit")
    print("*"*20)
    timetype = input(":")
    #opening almenus
    if timetype in ["b","Q"]:
        pass
    else:
        restartmenu()
    if timetype in ["s","S"]:
        restartsecondsmenu()
    if timetype in ["m","M"]:
        restartminutesmenu()
    if timetype in ["h","H"]:
        restarthoursmenu()
    if timetype in ["b","Q"]:
        exit()

#Seconds Menu
def restartsecondsmenu():
    os.system("cls")
    print("*"*20)
    print("How many seconds?")
    print("0-60 seconds")
    print("b = back")
    print("q = quit")
    print("*"*20)
    second = input(":")
    #Menu key fuctions
    if second in ["b","60"]:
        pass
    else:
        restartsecondsmenu()
    if second in ["b","B"]:
        restartmenu()
    if second in ["q","Q"]:
        exit()
    if second >= "0":
        #Restart with time
        os.system("shutdown.exe /r /t " + second)

#Minutes Menu
def restartminutesmenu():
    os.system("cls")
    print("*"*20)
    print("How many minutes?")
    print("(Just numbers!)")
    print("b = back")
    print("q = quit")
    print("*"*20)
    minutes = input(":")
    #Menu key fuctions
    if minutes in ["b","Q"] or "1" <= minutes:
        pass
    else:
        restartminutesmenu()
    if minutes in ["b","B"]:
        restartmenu()
    if minutes in ["q","Q"]:
        exit()
    if minutes >= "1":
        #Minutes Calculation
        minsec = str(int(eval(minutes) * 60))
        #Restart with time
        os.system("shutdown.exe /r /t " + minsec)

#Hours Menu
def restarthoursmenu():
    os.system("cls")
    print("*"*20)
    print("How many hours?")
    print("(Just numbers!)")
    print("b = back")
    print("q = quit")
    print("*"*20)
    hours = input(":")
    #Menu key fuctions
    if hours in ["b","Q"] or "1" <= hours:
        pass
    else:
        restarthoursmenu()
    if hours in ["b","B"]:
        restartmenu()
    if hours in ["q","Q"]:
        exit()
    if hours >= "1":
        #Minutes Calculation
        hoursec = str(int(eval(hours) * 3600))
        #Restart with time
        os.system("shutdown.exe /r /t " + hoursec)

#####################################################################################################
############################################Log off Menu#############################################
#####################################################################################################
def logoffmenu():
    os.system("cls")
    print("*"*20)
    print("Instant log off?:")
    print("y = yes")
    print("n = no")
    print("*"*20)
    timetype = input(":")
    #opening almenus
    if timetype in ["y","n","Y","N"]:
        pass
    else:
        logoffmenu()
    if timetype in ["y","Y"]:
        os.system("shutdown.exe /l")
    if timetype in ["n","N"]:
        def quit():
            os.system("cls")
            print("*"*20)
            print("Do you want to quit?")
            print("y = yes")
            print("n = no")
            print("*"*20)
            yesno = input(":")
            if yesno in ["y","N"]:
                pass
            else:
                quit()
            if yesno in ["y","Y"]:
                exit()
            if yesno in ["n","N"]:
                menu()
        quit()

#####################################################################################################
############################################Hibernate Menu###########################################
#####################################################################################################
def hibernatemenu():
    os.system("cls")
    print("*"*20)
    print("Instant hibernation:")
    print("y = yes")
    print("n = no")
    print("b = back")
    print("q = quit")
    print("*"*20)
    timetype = input(":")
    #opening almenus
    if timetype in ["y","N"]:
        pass
    else:
        hibernatemenu()
    if timetype in ["y","Y"]:
        os.system("shutdown.exe /h")
    if timetype in ["n","N"]:
                menu()
        quit()

menu()

这是角度应用程序中的相应服务调用

[Route("api/masterdata/general/companies")]
[ApiController]
public class CompanyController : Controller
{
    private DataContext DataContext;

    public CompanyController(DataContext dataContext)
    {
        DataContext = dataContext;
    }

    [HttpGet("{id}")]
    public Company GetCompany(long Id)
    {
        return DataContext.Companies.Find(Id);
    }

    [HttpGet]
    public IEnumerable<Company> GetCompanies()
    {
        return DataContext.Companies;
    }

    [HttpPost("validatename/{name}")]
    public JsonResult ValidateName(string name)
    {
        IEnumerable<Company> companies = DataContext.Companies;

        bool isValid = !companies.Any(c => Common.CleanName(c.Name) == Common.CleanName(name));

        return Json(isValid);
    }
}

为什么收到我的错误要求? validateName(name: string): Observable<any> { return this.http.post<boolean>("api/masterdata/general/companies/validatename/" + name,null); } api调用是f达到并且工作正常。

谢谢。

解决方法

尝试一下:

house_data["bedrooms"] = ''
house_data["bedrooms"] = house_data["Amenities"].str.extract("(\d*\.?\d+)",expand=True)



3       3
4       1
5       3
6       2
7       3
       ..
2096    3
2097    4
2098    3
2099    2
2100    3
Name: bedrooms,Length: 1213,dtype: object

或更好

var cleanName=  Common.CleanName(name);
var isValid = !DataContext.Companies.Any(c => Common.CleanName(c.Name) == cleanName);
return Json(new { isValid = isValid.ToString() });
,

问题是,我在ConfigureServices方法中注册了防伪令牌功能:

services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; });

但是我忘记将反伪造令牌添加到像这样的来自角度的请求中:

    app.Use(nextDelegate => context =>
    {
        string path = context.Request.Path.Value;
        string[] directUrls = { "/masterdata" };
        if (path.StartsWith("/api") || string.Equals("/",path) || directUrls.Any(url => path.StartsWith(url)))
        {
            var tokens = antiforgery.GetAndStoreTokens(context);
            context.Response.Cookies.Append("XSRF-TOKEN",tokens.RequestToken,new CookieOptions()
            {
                HttpOnly = false,Secure = false,IsEssential = true
            });
        }
        return nextDelegate(context);
    });

现在,它可以工作了(状态200)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。