标签: webapi2

如何为302状态代码使用handleexeption批注时如何指定位置

使用c#Web Api 2,我有抛出的代码InvalidOperationException.返回状态代码302时,如何使用HandleException注释为重定向提供位置?

[HandleException(typeof(InvalidOperationException), HttpStatusCode.Found, ResponseContent = "Custom message 12")]
public IHttpActionResult GetHandleException(int num)
{
     switch (num)
     {
          case 12: throw new InvalidOperationException("DONT SHOW invalid operation exception");

          default: throw new Exception("base exception");
     }
}
Run Code Online (Sandbox Code Playgroud)

编辑:对不起,我有点急忙问这个问题.上面的类使用HandleExceptionAttribute类,该类继承自ExceptionFilterAttribute.当我试图调试他们的单元测试时,我没有意识到这一点.单元测试中不会出现此问题,但使用需要重定向URL的Visual Studio .webtest会显示该问题.从ExceptionFilterAttribute继承的类未提供允许提供重定向URL的参数.对不起,问题不完整,谢谢你花时间回答.

/// <summary>
   /// This attribute will handle exceptions thrown by an action method in a consistent way
   /// by mapping an exception type to the desired HTTP status code in the response.
   /// It may be applied multiple times …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc visual-studio asp.net-web-api2 webapi2

7
推荐指数
1
解决办法
523
查看次数

在WebApi控制器的GET方法中使用[FromBody]

所以我知道如何使用[FromUri]WebApi[FromBody]控制器的“Post”方法。不用说[FromUri],“Get”方法是不必要的,但很明确,并且效果很好。我的问题是我希望 WebApi 在“Get”方法上解析我的 HttpBody 以填充我的对象参数。像这样...

public IHttpActionResult Get([FromBody]Customer c) {
   if (c is null) {
      // problem :-(
   }
}
Run Code Online (Sandbox Code Playgroud)

首先,让我解释一下我为什么要这样做。这是因为我的“获取”URL 很复杂。我需要在其中包含 JSON 对象。因此,虽然我知道使用 HTTP Body 作为“Get”上的有效负载并不是完美的 REST,但我还是愿意这样做。

其次,对于那些认为我应该将其包含在 URL 中的人……好吧,好吧。但是,请告诉我如何测试,因为我尝试在 URL 上输入 JSON 对象,浏览器引用了它的内容,但即使使用[FromUri]我的“获取”WebApi 控制器方法,我也无法解析它。我也尝试通过 Swagger 卷曲,但同样的问题。

我的 JSON 对象很简单{ "a" : "A", "b" : "B" }

预先感谢您的任何帮助。

c# rest swagger webapi2

6
推荐指数
0
解决办法
2万
查看次数

使用 dapper 进行分页的 TotalCount

我使用 dapper 将存储过程中的结果集获取到对象列表中,并将其作为 json 返回给客户端:

public IHttpActionResult Test()
    {
        List<ProductPreview> gridLines;
        var cs = ConfigurationManager.ConnectionStrings["eordConnection"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(cs))
        {
            gridLines = conn.Query<ProductPreview>("dbo.myStoredProcedure", new { userID = 1 },
             commandType: CommandType.StoredProcedure).ToList();
        }
        var totalCount = gridLines[0].MaxCount;//I need to know total count
        ....
        return Ok(gridLines);
    }
Run Code Online (Sandbox Code Playgroud)

有用。ProductPreview 类型的对象的最后一个属性是 TotalCount,因为存储过程将总计数作为每行的列返回。(第二个选项是存储过程返回两个记录集,但我不确定如何更改 dapper 以使用两个记录集)。不能选择进行两个单独的查询。

在没有 TotalCount 属性的情况下将 gridLines json 对象返回给客户端(因为它是开销)并将总计数从存储过程读取到某个变量的最佳方法是什么?将 gridLines 对象复制到没有 TotalCount 属性的其他对象也会产生不必要的开销。

c# dapper webapi2

4
推荐指数
1
解决办法
4569
查看次数

来自正文(布尔值)错误的 ASP.NET Web API 2 原始类型

我有一个动作

[HttpPatch]
public IHttpActionResult foo(int id, [FromBody]bool boolVariable)
{
 return Ok();
}
Run Code Online (Sandbox Code Playgroud)

我仍在调试,当我尝试用 Postman 发送一些数据时,我收到一个奇怪的错误

"Message": "请求无效。", "MessageDetail": "参数字典包含一个非空类型 'System.Boolean' 的参数 'boolVariable' 的空条目,用于方法 'System.Web.Http.IHttpActionResult foo (Int32, Boolean)' in 'ProjectName.Controllers.NameController'。可选参数必须是引用类型、可为空类型或声明为可选参数。”

问题是它没有将 boolVariable 与我的 json 主体绑定...是的,我可以使用绑定模型轻松解决问题

  public class FooBindModel
    {
        public bool boolVariable{ get; set; }
    }


public IHttpActionResult foo(int id, FooBindModel bindModel)
{
 return Ok();
}
Run Code Online (Sandbox Code Playgroud)

但是它困扰着我,为什么它不从 json 的主体中绑定变量?我在动作参数中指定 [FromBody] ...

api asp.net-web-api asp.net-web-api2 webapi2

4
推荐指数
1
解决办法
4421
查看次数

在发布版本中隐藏 api 端点

我正在开发一个 Asp.net Web api 项目。我最近使用创建了一个文档端点config.Services.GetApiExplorer();

在生产中隐藏此端点并仍然可供我团队中的所有其他开发人员使用的最佳方法是什么?

我能想到的一种方法是使用注册路线

#if debug

routes.MapRoute(
"documentation",
"documentation/help", 
new { controller = "apiexplorer", action
= "Index" }
);

#endif
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api asp.net-mvc-apiexplorer webapi2

2
推荐指数
1
解决办法
4711
查看次数

如何使用带有Owin的WebApi 2的swashbuckle生成文档

我使用这篇文章创建了一个WebApi项目.

事情很好.但现在我的客户想要使用Swagger查看文档.我试着做配置,但事情没有用.没有获得控制器列表及其操作.

在此输入图像描述

下面是招摇配置:

using System.Web.Http;
using WebActivatorEx;
using DC.SUMS.WebAPI1;
using Swashbuckle.Application;
using System;
using System.Linq;
using Swashbuckle.Swagger;
using Swashbuckle.Dummy.SwaggerExtensions;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace DC.SUMS.WebAPI1
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration 
                .EnableSwagger(c =>
                {

                        // By default, the service root url is inferred from the request used to access the docs.
                        // However, there may be situations (e.g. proxy and load-balanced environments) where this does not
                        // resolve correctly. You …
Run Code Online (Sandbox Code Playgroud)

swagger owin webapi2

1
推荐指数
1
解决办法
9635
查看次数

GetAsync:不返回HttpResponseMessage

应用程序应该从LoginUser()接收httpresponsemessage但它没有响应.

    private void button1_Click(object sender, EventArgs e)
    {
        if (LoginUser(tUser.Text, Password.Text).Result.IsSuccessStatusCode)
        {
            Notifier.Notify("Successfully logged in.. Please wait!");

        }
        else
        {
            Notifier.Notify("Please check your Credential..");
        }            
    }
Run Code Online (Sandbox Code Playgroud)
    public async Task<HttpResponseMessage> LoginUser(string userid, string password)
    {
        string URI = "http://api.danubeco.com/api/userapps/authenticate";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("c291cmF2OmtheWFs");

            using (var response = await client.GetAsync(String.Format("{0}/{1}/{2}", URI, userid, password)))
            {
                return response;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

请帮忙!

c# asynchronous async-await webapi2 httpresponsemessage

1
推荐指数
1
解决办法
2196
查看次数