我有一个使用ASP.NET开发的单页Web应用程序.我最近使用SignalR库将许多Web方法转换为基于推送的方法.这真的大大增加了页面,减少了页面上的大量服务器调用.
与此同时,我也一直在寻找RESTful ASP.NET WebAPI的一些服务器端方法,真正的美妙之处在于它允许在我开发的同时为外部应用程序创建API.核心应用程序(这对我正在做的事情很重要).
然而,在看了几篇文章和这 两个问题后,似乎推送和WebAPI方法似乎是两种完全不同的客户端 - 服务器通信范例.我敢肯定我可以创建各种方法,可以通过任何协议访问,但我不确定是否有这个陷阱或如果这被认为是草率 - 也许有一个更优雅的方式来实现我的目标对于.
在某种情况下,我希望RESTful WebAPI通过SignalR集线器广播事件......相反(SignalR需要访问WebAPI)似乎不太可能,但我认为仍然可能.
有没有人这样做过?有没有人对如何进行有任何建议或提示?这里最优雅的方式是什么?
我的WebAPI部署在Intranet环境中.这意味着安全不是我关注的问题.
看起来CORS 对客户端更友好,更容易实现.
我可能错过了任何其他问题吗?
我正在从WCF Web API转换为新的ASP.NET MVC 4 Web API.我有一个UsersController,我想要一个名为Authenticate的方法.我看到了如何进行GetAll,GetOne,Post和Delete的示例,但是如果我想在这些服务中添加额外的方法呢?例如,我的UsersService应该有一个名为Authenticate的方法,它会传入用户名和密码,但是它不起作用.
public class UsersController : BaseApiController
{
public string GetAll()
{
return "getall!";
}
public string Get(int id)
{
return "get 1! " + id;
}
public User GetAuthenticate(string userName, string password, string applicationName)
{
LogWriter.Write(String.Format("Received authenticate request for username {0} and password {1} and application {2}",
userName, password, applicationName));
//check if valid leapfrog login.
var decodedUsername = userName.Replace("%40", "@");
var encodedPassword = password.Length > 0 ? Utility.HashString(password) : String.Empty;
var leapFrogUsers = LeapFrogUserData.FindAll(decodedUsername, …Run Code Online (Sandbox Code Playgroud) 我在我创建的Web API中进行了以下操作:
// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public CartTotalsDTO GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
return delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh);
}
Run Code Online (Sandbox Code Playgroud)
对此Web服务的调用是通过以下方式通过Jquery Ajax调用完成的:
$.ajax({
url: "/api/products/pharmacies/<%# Farmacia.PrimaryKeyId.Value.ToString() %>/page/" + vm.currentPage() + "/" + filter,
type: "GET",
dataType: "json",
success: function (result) {
vm.items([]);
var data = result.Products;
vm.totalUnits(result.TotalUnits);
}
});
Run Code Online (Sandbox Code Playgroud)
我见过一些以这种方式实现上一个操作的开发人员:
// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public async Task<CartTotalsDTO> GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
return …Run Code Online (Sandbox Code Playgroud) 我正在阅读有关WebApi授权的几个资源(书籍和SO答案).
假设我想添加自定义属性,该属性仅允许特定用户访问:
情况1
我已经看到了这种覆盖的 方法, OnAuthorization如果出现问题就会设置响应
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if ( /*check if user OK or not*/)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
}
Run Code Online (Sandbox Code Playgroud)
案例#2
但是我也看到了这个类似的例子,它也覆盖了 OnAuthorization但是要求base:
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
// If not authorized at all, don't bother
if (actionContext.Response == null)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
然后,检查是否
HttpActionContext.Response已设置.如果未设置,则表示请求已获得授权且用户可以
案例#3
但我也看到了这种覆盖的方法IsAuthorized :
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
protected override …Run Code Online (Sandbox Code Playgroud) 如何从ASP.NET MVC Web API控制器返回HTML?
我尝试了下面的代码,但由于没有定义Response.Write,因此出现了编译错误:
public class MyController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
Response.Write("<p>Test</p>");
return Request.CreateResponse(HttpStatusCode.OK);
}
}
Run Code Online (Sandbox Code Playgroud) 您好我需要获取请求web api中的某些方法的客户端IP,我试图从这里使用此代码但它总是返回服务器本地IP,如何以正确的方式获取?
HttpContext.Current.Request.UserHostAddress;
Run Code Online (Sandbox Code Playgroud)
来自其他问题:
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud) 我是ASP.NET 4.0 Web API的新手.我们可以在POST操作结束时重定向到另一个URL吗?Response.Redirect(url)
实际上我www.abcmvc.com通过Web API(比方说www.abcwebapi.com/upload)从MVC应用程序上传文件(比如说)
这upload是POST动作.我将多部分表单发布到Web API上传控制器的后期操作.上传后我想重定向回www.abcmvc.com.
这可能吗?
我试图async/await在我的Web API项目中使用ASP.NET 的功能.我不确定它是否会对我的Web API服务的性能产生任何影响.请在下面找到我的应用程序中的工作流程和示例代码.
工作流程:
UI应用程序→Web API端点(控制器)→Web API服务层中的调用方法→调用另一个外部Web服务.(这里我们有数据库交互等)
控制器:
public async Task<IHttpActionResult> GetCountries()
{
var allCountrys = await CountryDataService.ReturnAllCountries();
if (allCountrys.Success)
{
return Ok(allCountrys.Domain);
}
return InternalServerError();
}
Run Code Online (Sandbox Code Playgroud)
服务层:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
return Task.FromResult(response);
}
Run Code Online (Sandbox Code Playgroud)
我测试了上面的代码并且正在运行.但我不确定它是否正确用法async/await.请分享你的想法.
ASP.NET Web API默认执行内容协商 - 将根据Accept标头返回XML或JSON或其他类型.我不需要/想要这个,有没有办法(比如属性或东西)告诉Web API总是返回JSON?
asp.net-web-api ×10
c# ×5
asp.net-mvc ×4
asp.net ×3
async-await ×2
ajax ×1
c#-4.0 ×1
cors ×1
html ×1
jquery ×1
jsonp ×1
rest ×1
signalr ×1