标签: asp.net-web-api

将web api中的$ Id映射到自定义ID

我有一个像SomeId这样的自定义ID的DTO.get请求以此格式返回返回JSON:

... "$id":"2","SomeId":1 ...
Run Code Online (Sandbox Code Playgroud)

在ApiController操作返回JSON之前,我可以以某种方式将SomeId映射到$ Id吗?

asp.net-mvc-4 asp.net-web-api

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

试图理解为什么这个工作/异步返回

我正在创建一个ASP.NET WebAPI 2控制器.它有效,但我很困惑.看来我正在返回List <..>而不是Task

请向我解释为什么返回列表是正确的.

public class AttendeePriceController : ApiController
{
    // GET api/<controller>
    public async Task<List<AttendeePrice>> Get()
    {
        List<AttendeePrice> attendeesPriceList;
        using (var db = new MyContext())
        {
            attendeesPriceList = await db.AttendeePrices.ToListAsync();
        }
        return attendeesPriceList;
    }
Run Code Online (Sandbox Code Playgroud)

c# async-await asp.net-web-api

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

如何使用angularjs调用带有两个参数的web api Controller方法

我是angularjs中的新手,我环顾四周试图在此找到一些帖子,但有很多但没有解决我的具体问题(我能找到).

就这么简单,我想通过angularjs($ http POST)发送两个参数,其中我的第一个参数是类对象的json,第二个是int.我尝试了什么:

        var url = '../Request/'+ id;
        $http({
            method: 'POST',
            url: url,
            data: Data
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).error(function (data, status, headers, config) {
            debug.error(data);
            deferred.reject('An error occured while saving the request');
        });
Run Code Online (Sandbox Code Playgroud)

在我的web api控制器中,我有:

    [POST("Request/{id}")]
    public bool SaveRequest(Data data, int id)
    {
       ...
       ...   
    }
Run Code Online (Sandbox Code Playgroud)

当我只发送数据时,它适用于我,但当我尝试添加Id和数据时,它都无法正常工作.请让我知道需要做些什么,谢谢.

asp.net-mvc-4 asp.net-web-api angularjs

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

如何在ASP.NET MVC4中捕获Web API中的表单授权错误

ASP.NET/Mono MVC4 Web API v.1应用程序.

API控制器使用表单授权,并使用标准[Authorize]属性进行修饰.如果授权失败,则标准api错误消息

<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>
Run Code Online (Sandbox Code Playgroud)

发生.如何通过写入日志文件来识别此错误.返回给调用者shoudl的错误消息保持不变.如何添加额外的代码,这可以写入此错误消息与整个http请求标头和正文到日志文件?

我从问题中添加了代码

如何为C#MVC4 WebAPI应用程序全局记录所有异常?

如何在ASP.NET MVC4 Web API中捕获未定义的api方法调用

但是没有抓住错误的错误.

如何捕捉所有错误?

更新

代码需要在Windows 2003服务器中运行.我从回答中尝试了代码,但遇到了编译错误

Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc asp.net-mvc-4 asp.net-web-api

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

REST URI优于查询字符串格式的URI的优点?

所有,

对于我们从.NET开始的新项目,我们想要运行纯REST.因此,我们选择.NET Web API作为.NET Framework 4.5(而不是WCF)的一部分发布,并考虑到它支持纯REST特性.但是,当我们根据我们的要求进行更多探索时,我们意识到它没有提供类似URL格式的REST的URI模板支持.我们仍然可以,因为我们对具有查询字符串格式的WebAPI感觉不太好.

当我们聘请一个新团队时,他们开始强制执行他们需要REST类型的URL格式,因为它是标准规范和喜欢.

当被问及执法时,他们刚刚提到它是一个标准,我们必须坚持它,这并不能说服我.

所以,我有兴趣知道REST架构提供了什么?还有querystring格式的URI不符合REST方法吗?

REST URI:http://myapplicationdomain.com/apps/appId

查询字符串URI:http://myapplicationdomain.com/GetAps/appId= {appId}

提前致谢.

c# asp.net rest wcf asp.net-web-api

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

WebApi HelpPage HttpResponseMessage SetActualResponseType

我正在使用MVC4项目中的WebApi帮助页面.

根据以下链接,http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples- on-the-help-page.aspx我一直在设置HelpPageConfig来设置实际的响应类型.

我有一个控制器,它有两个get方法

/// <summary>
/// Get the list of plans for a specified portfolio
/// </summary>
/// <param name="portfolioIdentifier">Portfolio Identifier (guid)</param>
/// <returns>
/// Returns a list of <see cref="RestDTOs.Plan"/> Plan objects
/// </returns>
    public HttpResponseMessage Get(Guid portfolioIdentifier)
    {
    }

/// <summary>
/// Get full plan details.
/// </summary>
/// <param name="planIdentifier">Plan Identifier (guid)</param>
/// <returns>
/// Returns the <see cref="RestDTOs.Plan"/> Plan object
/// </returns>
[HttpGet]
    public HttpResponseMessage Detail(Guid planIdentifier)
    {
    }
Run Code Online (Sandbox Code Playgroud)

在HelpPageConfig.cs中,我添加了以下内容以尝试设置ResponseBody格式示例

config.SetActualResponseType(typeof(Plan), "Plan", "GET"); …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc-4 asp.net-web-api

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

找不到asp.net web api 2属性路由

我在一个名为的API控制器中有这个路由Recruiting:

 ResponseType(typeof (int))]
 [Route("Recruiting/setprimary/")]
 public async Task<IHttpActionResult> PutUpdatePrimary(string userId, string orgId)
 {
     return Ok();
 }
Run Code Online (Sandbox Code Playgroud)

我试图通过像ajax这样的路由:

 self.updatePrimary = function () {
    var orgKey = self.selectedOrgKey();
    alert(orgKey);
    $.ajax({
        type: "PUT",
        contentType: "application/json; charset=utf-8",
        url: "/Recruiting/setprimary/" + "?userId=" + userId + "&?orgId=" + orgKey,
        data: null,
        dataType: "json",
        success: function (data) {
            bootbox.alert('Changes saved successfully.');
        },
        error: function (err) {
            bootbox.alert('An error occured while trying to set primary organisation. Please try again :/');
        }
    });
    return true;
};
Run Code Online (Sandbox Code Playgroud)

提琴手说它无法找到路线.这里有什么问题?

asp.net asp.net-web-api

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

如何在Web API中使用C#获取Foursquare OAuth请求代码?

我正在使用SharpSquare进行Foursquare API的C#建模,我在第1步陷入困境.

  1. 从Foursquare获取"代码"
  2. 根据返回网址和"代码"获取访问令牌
  3. 查询API

SharpSquare文档显示了这一点:

if (Request["code"] != null) {
    sharpSquare.GetAccessToken(redirectUri, Request["code"]);
    ...
}
else {
    HyperLink.NavigateUrl = sharpSquare.GetAuthenticateUrl(redirectUri);
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试从ASP.NET Web API方法中查询Foursquare API .我不能这样做: HyperLink.NavigateUrl = sharpSquare.GetAuthenticateUrl(redirectUri);

我该怎么做才能获得"代码"?(我已经尝试了各种WebClient()和WebRequest/WebResponse尝试,只是不能让它工作).

c# foursquare asp.net-web-api sharpsquare

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

Web API控制器路径?

我是Web API的新手并遵循一些示例,但我无法确定指定控制器名称的位置.

我在global.asax中有这个:

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute(
    name: "API Controller",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
    );
}
Run Code Online (Sandbox Code Playgroud)

我有一个名为TestAPI.cs的Controller

这是内容:

namespace Testing
{
    public class TestAPI : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            string test= "Hello!";
            return test
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我只在其中放置"返回测试"作为Stack Overflow的一个例子,因为它包含很多代码.

所以,如果我在jQuery中使用它,我将使用什么路径的控制器?

c# asp.net-web-api asp.net-web-api2

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

使用Web API在MVC中进行Knockout Paging

我无法将此代码转到页面.表的页面大小始终相同 - 从Web API调用返回的项目数.传入的参数被忽略(3).此外,后退和前进按钮元素没有图标(图标 - 后退图标 - 前进 - 后退),但这是页面大小的次要.

HTML

<table class="table">
    <thead>
        <tr>
            <th data-column="LastName">Last Name</th>
            <th data-column="FirstName">First Name</th>
            <th data-column="EnrollmentDate">Enrollment Date</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: students">
        <tr>
            <td data-bind="text: LastName" />
            <td data-bind="text: FirstName" />
            <td data-bind="text: EnrollmentDate" />
        </tr>
    </tbody>

    <tfoot>
        <tr>
            <td>
                Number of items per page:
                <select id="pageSizeSelector" data-bind="value: pageSize">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option> …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc asp.net-web-api knockout.js

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