使用ASP.NET Web API.如果参数为空,有没有办法自动返回状态代码400?我发现了这个问题,但这是一个应用于所有方法的全局解决方案,我想在每个参数的每个方法的基础上执行此操作.
所以,例如,这就是我目前正在做的事情:
public HttpResponseMessage SomeMethod(SomeNullableParameter parameter)
{
if (parameter == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
// Otherwise do more stuff.
}
Run Code Online (Sandbox Code Playgroud)
我真的只想做这样的事情(注意所需的属性):
public HttpResponseMessage SomeMethod([Required] SomeNullableParameter parameter)
{
// Do stuff.
}
Run Code Online (Sandbox Code Playgroud) 我看过以下内容:
我的终点:
[HttpPost]
[Route("/getter/validatecookie")]
public async Task<IActionResult> GetRankings([FromBody] string cookie)
{
int world = 5;
ApiGetter getter = new ApiGetter(_config, cookie);
if (!await IsValidCookie(getter, world))
{
return BadRequest("Invalid CotG Session");
}
HttpContext.Session.SetString("cotgCookie", cookie);
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
我的请求:
$http.post(ENDPOINTS["Validate Cookie"], cookie , {'Content-Type': 'application/json'});
Run Code Online (Sandbox Code Playgroud)
cookie我从用户输入发送的字符串在哪里.
请求使用适当的数据发布到端点.但是,我的字符串始终为null.我已经尝试删除[FromBody]标记,并=在发布的数据前添加一个没有运气.我还尝试使用上述所有组合添加和删除不同的内容类型.
我正在做这个具体行动的原因很长,对这个问题无关紧要.
无论我做什么,为什么我的参数总是为null?
编辑:我也尝试过使用 {cookie: cookie}
Edit2:请求:
Request URL:http://localhost:54093/getter/validatecookie
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:54093
Run Code Online (Sandbox Code Playgroud)
响应标题
Content-Type:text/plain; …Run Code Online (Sandbox Code Playgroud) public class MyModel
{
[JsonProperty(PropertyName = "foo", Required = Required.Always)]
public String Bar;
}
public class MyController : ApiController
{
public String PostVersion1([FromBody] MyModel myModel)
{
if (ModelState.IsValid)
{
if (myModel.Bar == null)
return "What?!";
else
return "Input is valid.";
}
else
{
return "Input is invalid.";
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
Input |Output
-------------------|------
{ "bad" : "test" } | What?!
{ "Bar" : "test" } | What?!
{ "foo" : "test" } | Input is valid.
Run Code Online (Sandbox Code Playgroud)
显然支持JsonPropertyAttribute,因为我能够设置PropertyName并使其生效.但是,我希望ModelState.IsValid前两个示例输入为false,因为 …
我正在使用.Net 4.5.1创建一个使用MVC 6的ASP.Net 5应用程序.我有一个POST方法,它使用FromBody参数自动获取对象.
[HttpPost]
public IActionResult Insert([FromBody]Agent agent)
{
try
{
var id = service.Insert(agent);
return Ok(id);
}
catch (Exception ex)
{
return HttpBadRequest(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这只是一个概念的证明,我不会只返回成功的id或错误的完整异常.
当发送有效的JSON时,一切正常.但是,当发送无效的JSON时,我在调试期间收到异常:
抛出异常:Newtonsoft.Json.dll中的'Newtonsoft.Json.JsonReaderException'
附加信息:解析值后,遇到意外字符:l.路径'名称',第2行,第20位.
问题是在此错误之后,该方法被正常调用,但是使用null参数,并且异常不会传播.
我可以检查null并返回一个通用消息,但这并不像原始消息那样有用,它包含重要信息,例如标记名称和无效字符的位置.
所以我想捕获此异常并将其返回给HTTP调用者.我怎么做?像这样的东西:
{"error": "After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20"}
Run Code Online (Sandbox Code Playgroud)
我知道我可以在try/catch块中手动捕获和反序列化JSON,但这对我来说是不可接受的.我想这样做并继续使用FromBody,我发现它很有效率.
我想在C#中也用C#调用ApiController,但是从WebClient实例使用UploadString方法上传Json时出现错误415或400。
服务器代码是自动生成的调用TestController。该文件正是Visual Studio 2019生成文件的方式。
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// POST: api/Test
[HttpPost]
public void Post([FromBody] string value)
{
}
...
}
Run Code Online (Sandbox Code Playgroud)
客户端代码如下所示:
WebClient client = new WebClient();
client.UploadString("https://localhost:44345/api/Test", "ABC"); // Edit: "ABC" is not a valid JSON
Run Code Online (Sandbox Code Playgroud)
我收到 System.Net.WebException:'远程服务器返回错误:(415)不支持的媒体类型。
因此,在谷歌搜索之后,大多数建议是如果我添加,ContentType不会得到指定
client.Headers[HttpRequestHeader.ContentType] = "application/json";
Run Code Online (Sandbox Code Playgroud)
我得到System.Net.WebException:'远程服务器返回错误:(400)错误的请求。
有什么线索吗?
似乎问题与POST/ PUT/ PATCH... 有关,如果执行了GET,它正在工作并向我返回示例数据["value1","value2"]
编辑:我不坚持使用WebClient.UploadString方法,但是我想要一个不涉及25行自定义代码的解决方案...我的意思是我不敢相信在jQuery中使用它可以做到这一点很难一行。