标签: asp.net-web-api

使用ASP.NET Web API输出Atom提要

在我的ASP.NET Web API项目中,我有一些标准的Edit API调用,其中XML或JSON输出或者调用者想要的任何内容都可以.但是有些调用应该返回ATOM提要.

现在我发现在这篇文章中我可以通过自定义MediaTypeFormatter实现ATOM或RSS输出:如何使用ASP.NET Web API生成ATOM和RSS2源?

但它实际上并不是我想要的,因为仍然由调用者通过HTTP Accept-header请求这样的输出.我想在这里专门返回ATOM,没有JSON,没有(序列化对象)XML.

是否可以使用Web API执行此操作?或者为这些调用使用标准Web控制器并仅将所有其他API调用实现为ApiControllers会更好吗?

谢谢你的帮助!

asp.net-web-api

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

在asp.net WebAPI控制器中这是一个可靠/建议的方式来获取http或https?

下面是我的索引控制器的示例.我想知道是否有更好,更可靠的方法来确定流量是否为https.

  public ActionResult IndexTest1(string year)
    {
        var isSecure = 
           ControllerContext.RequestContext.HttpContext.Request.IsSecureConnection;
Run Code Online (Sandbox Code Playgroud)

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

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

WebApi路由没有传递值

我试图将值传递给Web Api中的控制器/操作,但它没有找到它.

我的路线图:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

我的ApiController:

    [HttpGet]
    public string MyThing()
    {
        return "thing";
    }

    [HttpGet]
    public string MyStuff(int myid)
    {
        return "something " + myid;
    }
Run Code Online (Sandbox Code Playgroud)

通过RestSharp我的REST调用:

var request = new RestRequest { Resource = "api/values/MyStuff/555", Method = Method.GET };
Run Code Online (Sandbox Code Playgroud)

如果我称MyThing()它有效.似乎问题在于传递id值.

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

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

ASP.NET Web API异常过滤器 - 从HttpRequestBase获取请求URL的方法?

我已经为我的Web API实现了一个自定义异常过滤器.它按预期工作,除了一个小细节......

在以下代码示例中,SaveToErrorLog保存异常详细信息并尝试从context.Request.RawUrl获取请求URL.但context.Request不包含API在发生异常时尝试提供的URL.有没有办法在使用像这样的异常过滤器时获取URL?

public class APIExceptionFilter : ExceptionFilterAttribute
{
    private HttpContextBase context;

    public APIExceptionFilter() 
    {
        context = new HttpContextWrapper(HttpContext.Current);
    }

    public override void OnException(HttpActionExecutedContext actionContext)
    {
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);       
        if (actionContext != null && context != null)
        {
            facade.SaveToErrorLog(actionContext.Exception, context.Request);
        }     

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {               
            Content = new StringContent(actionContext.Exception.Message),
            ReasonPhrase = "APIException"
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

.net asp.net asp.net-mvc exception asp.net-web-api

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

Asp.net MVC4 Web API XML序列化忽略了公共属性

我正在使用asp.net mvc4 web api.我有一些由Devart Entity Developer生成的类,它们具有以下结构:

[Serializable]
[XmlRoot("Test")]
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
    [XmlAttribute("property1")]
    [JsonProperty("property1")]
    public int Property1
    {
        get { return _Property1; }
        set
        {
            if (_Property1 != value)
            {
                _Property1 = value;
            }
        }
    }
    private int _Property1;

    [XmlAttribute("property2")]
    [JsonProperty("property2")]
    public int Property2
    {
        get { return _Property2; }
        set
        {
            if (_Property2 != value)
            {
                _Property2 = value;
            }
        }
    }
    private int _Property2;
}
Run Code Online (Sandbox Code Playgroud)

我有这样的类的测试控制器:

public class TestController : ApiController
{
    private List<Test> _tests = new …
Run Code Online (Sandbox Code Playgroud)

xml asp.net asp.net-mvc xml-serialization asp.net-web-api

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

.Net web api,SSL + basic auth

我有多组传感器网络将数据发送到.net web api.不知何故,我需要保护API的一些端点(以便我可以确定发送到API的信息确实来自传感器).基本身份验证和SSL似乎是一种方法.问题是我无法理解SSL部分.

截至目前,我已经创建了存储在传感器上的客户端证书,可以通过Request.GetClientCertificate()方法在API中检索证书的信息.当我只是想用基本的身份验证来保护我的Api时,这是否有点过分?也就是说,只需通过https发送数据而不提供证书,通信是否安全?

我不需要使用证书进行身份验证(因为这是通过基本身份验证完成的).

ssl basic-authentication asp.net-web-api

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

如何将httpclient发布到WEB API?(我的高分榜的简单方法)

我的Windows Phone客户端发送一段代表名称和分数的JSON ......我应该使用Web API中的Class吗?将对象发送到服务器而不是原始json的代码是什么?

 private void btnCreateSampleScore_Click(object sender, RoutedEventArgs e)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");

            var content = new FormUrlEncodedContent(new[] 
                                                   {
                                                       new KeyValuePair<string, string>("Bob", "2.65")
                                                   });

            var result = client.PostAsync("/api/DrunkMeterScore", content).Result;

            string resultContent = result.Content.ReadAsStringAsync().Result;
            Console.WriteLine(resultContent);

            //DrunkMeterScore dms = new DrunkMeterScore();
            //dms.Name = "Bob";
            //dms.Score = 2.42;
        }

    }
Run Code Online (Sandbox Code Playgroud)

服务器正在使用纯Web API模板

 // POST api/DrunkMeterScore
    public HttpResponseMessage PostDrunkMeterScore(DrunkMeterScore drunkmeterscore)
    {
        if (ModelState.IsValid)
        {
            db.DrunkMeterScores.Add(drunkmeterscore);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, drunkmeterscore);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", …
Run Code Online (Sandbox Code Playgroud)

post httpclient asp.net-web-api

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

在C#中创建模型类?

所以我只是有一个简单的Web API,返回JSON格式如下

{
"dailyDealId": "432",
"discountPercentage": "0",
"product": {
    "productId": "10",
    "brandId": "10",
    "departmentId": "3",
    "name": "Baby Girl Velour Tunic & Snowflake Legging Set",
    "description": "The pretty set",
    "url": "http://whatever.whatever.com/files/whatever.tif"
}
Run Code Online (Sandbox Code Playgroud)

}

我想在我的C#控制台代码上获取这些数据

这是我的Model Class Data.cs

class Data
{
    public string dailyDealId { get; set; }
    public string discountPercentage { get; set; }
    public Array product { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要代码

static void Main(string[] args)
    {

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://whatever.com/");

        HttpResponseMessage response = client.GetAsync("product/").Result; …
Run Code Online (Sandbox Code Playgroud)

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

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

asp.net web api odataNo IdLink

我正在使用带有web api的Odata并收到此错误:

 <m:innererror>
<m:message>
The 'ObjectContent`1' type failed to serialize the response body for content type       'application/json; charset=utf-8'.
</m:message>
<m:type>System.InvalidOperationException</m:type>
 <m:stacktrace/>
<m:internalexception>
 <m:message>
No IdLink factory was found. Try calling HasIdLink on the EntitySetConfiguration for    'Tag'.
</m:message>
 <m:type>System.InvalidOperationException</m:type>
Run Code Online (Sandbox Code Playgroud)

这是我的OData配置:

  config.Routes.MapODataRoute("ODataRoute", "odata", CreateModel());
   static IEdmModel CreateModel()
    {
        var modelBuilder = new ODataModelBuilder();

        modelBuilder.EntitySet<Tag>("Tag");
        modelBuilder.EntitySet<Post>("Post");

        return modelBuilder.GetEdmModel();
    }
Run Code Online (Sandbox Code Playgroud)

这是我的OData控制器

  public class TagController : EntitySetController<Tag, int>
{
    private readonly IUnitOfWork _unitOfWork;

    public TagController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }


    public override IQueryable<Tag> Get() …
Run Code Online (Sandbox Code Playgroud)

odata asp.net-web-api asp.net-web-api-odata

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

C#异步方法 - 需要帮助

我有一个消耗Web API操作的异步方法.它似乎陷入了一个循环.我的理由是因为如果我在catch块的第1行放置一个断点,并且进入,它实际上从未击中第二行.

我最初返回一个包含100,000+(~30mb)行的数据集,并认为由于请求的大小,它可能会很慢,但在更改我的Web API操作以仅返回1行后问题仍然存在.当我浏览到Web API解决方案的URI时,肯定会返回数据,我在浏览器中返回了JSON.

public async Task<IEnumerable<Document>> GetAll()
{
    try
    {
        var response = await _client.GetAsync(
                       string.Format("{0}/api/document", _baseURI));

        // never hits line below
        return await response.Content.ReadAsAsync<Document>() 
                   as IEnumerable<Document>;
    }
    catch (Exception ex)
    {
        // handle exception
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定我在这里遗失了什么?一些帮助将不胜感激.

编辑1

在回答一些问题时,我有一个由MVC项目引用的Web API项目.我必须对JSON反序列化的原始问题进行一些更改.

库:

public async Task<IEnumerable<Document>> GetAll()
{
    try
    {
        string json;
        var response = await _client.GetAsync(string.Format(
                       "{0}/api/document", _baseURI)).ConfigureAwait(false);

        var resource = await response.Content.ReadAsAsync<Document>();

        using(var reader = new StreamReader(resource.ToString()))
        {
            json = reader.ReadToEndAsync().ToString();
        }

        return JsonConvert.DeserializeObjectAsync<Document>(json) 
                       as IEnumerable<Document>;
        } …
Run Code Online (Sandbox Code Playgroud)

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

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