Quantcast
Channel: Web API
Viewing all 4850 articles
Browse latest View live

asp.net web api oauth + third party like facebook

$
0
0

I've made api server for my service using asp.net web api + oauth2 authentication.

Currently our client device are android, iOS, angularJS web.

Everything was okay except adding third party oauth2 provider.

There are many service using like facebook join and login.

So I need to add this third party to add an account in our service and login without entering login info.

currently our oauth grant type is "Resource owner credentials grant", since I see ourgrant_type is 'password'

How do I add another login process to our existing login process?

How do I get token without name and password? is it possible or what?

Now I think of using client_id and client_secret to distinguish third party oauth providers.

client_id for providers

client_secret for telling a user, It's unique key in third party.

so if client_id is third party, then I take another routine in the login process.

I don't know  whether what I am saying is possible or not.

I don't know if you understand what I am saying, if not, let me know.

I really appreciate your help, 

I have many things to say but I am not an native english speaker. thus I am not free at saying what I want.

anyhow thank you.


WebAPI authorization token sometimes not working between webforms/webApi

$
0
0

I have ASP.Net web forms project & ASP.Net Web API  .

We have mobile app that open login page from web forms portal then I requested token requested from WebAPI for the current login user and save token in cookie after that mobile application consumed secured WebAPIs by passing generated token then sometimes the generated token return 401 unauthorized with following message :

{"Message": "Authorization has been denied for this request."
}

However when I used the same token in second time its working successfully via Postman/mobile .

So let me show scenarios I have right now :

1 - Token working fine for short period then unauthorized

2- Token not working for the first time then in the second time its working

3- Token not working all the time

Do you have any clue ?

how to enable mix mode for asp.net web forms app

$
0
0

Hi,

I have a .net framework 2.0 dll for AX 4.0 business connector that I need it working in new .net 4.7.1 Web API project.

I tried but it is not working , it throw error said the application is in break mode.

but It works well in windows form app same 4.7.1 by add useLegacyV2RuntimeActivationPolicy to app.config

<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
</startup>

I tried to add this to Web API, web.config , but it does not works, how can I make the web API project enable the mix mode like windows form app?

Regards,

Unable to exclude Folders during Deployment or Publish using VS2015

$
0
0

I have a Web API project which has some folders that needs to be included only when I am using Mock configurations. Release and QA should never have these folders after the deploy. Previously I was using VS2013 and things where working fine. Recently i switched over to VS2015 and things are broken.

With any publish or deployment the folders are also getting deployed to the servers which are causing issues. I am using "wpp.targets" method mentioned on this site "https://docs.microsoft.com/en-us/aspnet/web-forms/overview/deployment/advanced-enterprise-web-deployment/excluding-files-and-folders-from-deployment" to exclude the folders.

Can anyone please let me know if there is any additional steps required for VS2015 ?

WebAPI Call ajaxs request from client Chrome is not working

$
0
0

HI,

   I have created webapi and i have added CORS . By using ajaxs request from client , working in IE but Chrome not working.

Error in chrome

OPTIONS http://localhost:53693/api/SOP/1 0 () 

Angular Js Version and Visual Studio Version

$
0
0
Hi everyone!
I have got an assignment to implement CRUD and some other functionalities.
Stack is .Net MVC 5, Web API and Angular Js of my choice (between 2,4 or 5). I am very new to angular js and open to learn any version.
Which version should I learn and implement?

Will Visual Studio 2013 be enough?
Or should I use Visual Studio 2015 or 2017?

My previous projects were in 2013 so have been using that.

Thank You. Happy Coding!

How can I use the ASP.NET WEB API with REST

$
0
0

How can I use the ASP.NET WEB API with REST

Applying filters on nested object in OData.

$
0
0

Hi,

    I am writing a new OData service and my controller looks like below.

[EnableQuery]publicclassPeopleController:ODataController{publicIHttpActionResultGet(){returnOk(DemoDataSources.Instance.People.AsQueryable());}}

Everything works fine. Now my requirement is my response object will be wrapped with additional data as below.

   

[EnableQuery]publicclassPeopleController:ODataController{publicIHttpActionResultGet(){MyResult res =newMyResult();
            res.ConvId="123";
            res.TransId="123123";
            res.Result=DemoDataSources.Instance.People.AsQueryable();returnOk(res);}}publicclassMyResult{[Key]publicstringTransId{get;set;}publicstringConvId{get;set;}publicIQueryable<Person>Result{get;set;}}

My webapiconfig.cs looks like below.

privatestaticIEdmModelGetEdmModel(){ODataConventionModelBuilder builder =newODataConventionModelBuilder();
            builder.Namespace="Demos";
            builder.ContainerName="DefaultContainer";
            builder.EntitySet<Person>("People");var edmModel = builder.GetEdmModel();return edmModel;}

 

When I query using people, getting error "HTTP ERROR 406". 

How to apply queries on Result property on my custom class (MyResult in above scenario)..

Thanks,

sanjay.


Inserting middleware before a .Net Framework WebAPI call

$
0
0

Hello All,

Following John Atten's (kind of old) tutorial I am trying to layout a program structure similar to this picture (minus the authentication). I have a functional RESTful application, self-hosted via OWIN that callsUseWebApi() and all the expected models and controllers. Works well. I need to add some logging and also do some setup work before responding to requests.

Rather than manually formatting code in these forums I have created a StackOverflow question here. Anyone have any suggestions or feedback? Is there any documentation on MSDN somewhere explaining how to handle middleware in series with UseWebApi? Am I going about it the wrong way? John's posts are kind of old...

Also, .Net Framework WebAPI and .Net Core or entirely distinct, correct? "Core" tags were added to the SO post above, I'm not sure why.

Thanks in advance!

JB

Asp.net Core 2.0 Web Api Code First not working after successfully deployed to Local IIS

$
0
0

hi I am newbie in asp.net Core 2.0 web Api.  I was unable to find out the problems after many hours of trying. Please help.

I have successfully created a Sql Server Database with Code First approach but I encountered some problem in doing CRUD with Web Api thru PostMan.

----A) Creating a Database with Code First approach

1) This is my appsettings.json

"connectionstrings": {
"Default": "Server = .\\SQL2017Express; Database = ContactDB; Integrated Security = True;"
},

2) in startUp class

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ContactContext>(option => option.UseSqlServer (Configuration.GetConnectionString("Default")));
}

------- B) using DbContext and Model and repository approach

1) DbContext

using aspCoreWebApiUserDb.Models;
using Microsoft.EntityFrameworkCore;

namespace aspCoreWebApiUserDb.DataContext
{
public class ContactContext : DbContext
{
public ContactContext(DbContextOptions<ContactContext> options)
: base(options) { }
public ContactContext() { }
public DbSet<Contacts> Contacts { get; set; }
}
}

2) Model

public class Contacts
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobilePhone { get; set; }
}

3) using  IContactRepository and ContactRepository

public interface IContactRepository
{
Task Add(Contacts item);
Task<IEnumerable<Contacts>> GetAll();
Task<Contacts> Find(string key);
Task Remove(string Id);
Task Update(Contacts item);

bool CheckValidUserKey(string reqkey);
}

using Microsoft.EntityFrameworkCore;
using aspCoreWebApiUserDb.Models;
using aspCoreWebApiUserDb.DataContext;

namespace aspCoreWebApiUserDb.DataLayerRepository
{
public class ContactRepository : IContactRepository
{
ContactContext _context;
public ContactRepository(ContactContext context)
{
_context = context;
}

public async Task Add(Contacts item)
{
await _context.Contacts.AddAsync(item);
await _context.SaveChangesAsync();
}

public async Task<IEnumerable<Contacts>> GetAll()
{
return await _context.Contacts.ToListAsync();
}

public bool CheckValidUserKey(string reqkey)
{
var userkeyList = new List<string>
{
"28236d8ec201df516d0f6472d516d72d",
"38236d8ec201df516d0f6472d516d72c",
"48236d8ec201df516d0f6472d516d72b"
};

if (userkeyList.Contains(reqkey))
{
return true;
}
else
{
return false;
}
}

public async Task<Contacts> Find(string key)
{
return await _context.Contacts
.Where(e => e.MobilePhone.Equals(key))
.SingleOrDefaultAsync();
}

public async Task Remove(string Id)
{
var itemToRemove = await _context.Contacts.SingleOrDefaultAsync(r => r.MobilePhone == Id);
if (itemToRemove != null)
{
_context.Contacts.Remove(itemToRemove);
await _context.SaveChangesAsync();
}
}

public async Task Update(Contacts item)
{
var itemToUpdate = await _context.Contacts.SingleOrDefaultAsync(r => r.MobilePhone == item.MobilePhone);
if (itemToUpdate != null)
{
itemToUpdate.FirstName = item.FirstName;
itemToUpdate.LastName = item.LastName;
itemToUpdate.MobilePhone = item.MobilePhone;
await _context.SaveChangesAsync();
}
}
}
}

--- 4) create a  ContactController

using aspCoreWebApiUserDb.Models;
using aspCoreWebApiUserDb.DataContext;
using aspCoreWebApiUserDb.DataLayerRepository;

namespace aspCoreWebApiUserDb.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class ContactsController : Controller
{
public IContactRepository ContactsRepo { get; set; }

public ContactsController(IContactRepository _repo)
{
ContactsRepo = _repo;
}

[HttpGet]
public async Task<IActionResult> GetAll()
{
var contactList = await ContactsRepo.GetAll();
return Ok(contactList);
}

[HttpGet("{id}", Name = "GetContacts")]
public async Task<IActionResult> GetById(string id)
{
var item = await ContactsRepo.Find(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}

[HttpPost]
public async Task<IActionResult> Create([FromBody] Contacts item)
{
if (item == null)
{
return BadRequest();
}
await ContactsRepo.Add(item);
return CreatedAtRoute("GetContacts", new { Controller = "Contacts", id = item.MobilePhone }, item);
}

[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, [FromBody] Contacts item)
{
if (item == null)
{
return BadRequest();
}
var contactObj = await ContactsRepo.Find(id);
if (contactObj == null)
{
return NotFound();
}
await ContactsRepo.Update(item);
return NoContent();
}

[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
await ContactsRepo.Remove(id);
return NoContent();
}
}
}

Deploy this Web api app to IIS ( Local Machine):

This project has no compilation error, it was build successfully. I have also successfully deployed this Asp.net Core 2.0 WebApi to local Machine IIS.

----testing Check:

a) Note: have checked that SQL Server 2017 is running in Services under Control panel

b) Have tested the Default ValuesController in the WebApi Template
I was able to get the values with Get : http://192.168.1.8:8989/api/values

c) I have manually create some data in the table using SSMS for SQL Server 2017

here the problems when using Postman to do CRUD. (All app are in this PC (Local machine): Postman and IIS).

1) do a Post with Postman

Post : http://192.168.1.8:8989/api/contacts

Json Data for the Body in PostMan:

{
"FirstName" : "John",
"LastName" : "David",
"MobilePhone" : "123456789"
}

problem :  status 500 internal server Error

2) Do a get with PostMan

GET : http://192.168.1.8:8989/api/contacts


Problem: status 500 internal server Error

What seems to be the problem? I need your help.  Thanks

JSON Deserializing fails: Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: e.

$
0
0

Whenever I’m running a DeserializeObject command to convert JSON to C# object, I’m getting the JsonReaderException, and the process stops at this line in my JSON:

\"emails\": [account%40mydomain.com],\n\t\ (which equals to "emails": "[account@mydomain.com]")

I’m doing the actual deserialization by using these lines of code:

var body = actionContext.Request.Content.ReadAsStringAsync().Result;

var chRequest = JsonConvert.DeserializeObject<MyObject>(body);

All the other fields (almost 20 of them) in the JSON message gets deserialized without issues. The process fails on the lines where I process arrays (there is another array in the JSON message, which fails with the same message).

In MyObject, Emails property looks like this:

[JsonProperty("emails")]

public string Emails { get; set; }

The data is coming from an external system by using POST method. It is sent asapplication/x-www-form-urlencoded.

After trying to figure this out this issue for days, I’d really like to get some fresh ideas on how to solve this.

How to create a url string to use in browser address bar

$
0
0

Hello,

I'm trying to figure out how to create a url to manually test an API. I'm talking about a string of characters that I can enter into my browsers address bar and when I press enter, it processes the string.

I'm working with the company whose API information is here.

If my key is "xyz" and if I use a string like: "https://secure.chinavasion.com/api/getProductList.php?key=xyz&categories="Cell Phone Watch" in the address bar, I get thiserror.

Does anybody know how to compose a url string to test this manually?

Thanks,
Tony

Built a RESTful API .. now what ... how can I display the json results in the simplest index.html page?

$
0
0

Built a RESTful API .. now what ... how can I display the json results in the simplest index.html page? 

My api reads columns and rows from a mssql database table

Could someone please help me out with a hello world example of an index.html page that calls my servicehttp://myserver/api/servemejsondata and displays the json results ? 

Thank You. :-) 

working with cookies in a Message Handler

$
0
0

Hello All,

This question pertains to 4.6.1 in VS2017.

I am following the docs here for getting cookie data from a request:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-cookies#example-set-and-retrieve-cookies-in-a-message-handler

I have been working with the HttpRequestMessage for a while, no problem. However, in the sample code above:

request: type HttpRequestMessage

request.Headers: type HttpRequestHeaders

According to the class docs:

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.headers.httprequestheaders?view=netframework-4.6.1#methods-

This type does not have a GetCookies() method, however VS2017 shows one to be available. Using that method with:

var cookie = message.Headers.GetCookies();

cookies.GetType() returns: System.Collections.ObjectModel.Collection`1[System.Net.Http.Headers.CookieHeaderValue] (`1 wha???)

cookies[0].GetType() returns: System.Net.Http.Headers.CookieHeaderValue

That type also does not exist in the class docs for HttpHeaders.

Accessing cookies[0].ToString() gives me a string with all the cookie values in it as a semi-colon delimited string.

Are we supposed to parse this string to obtain cookie key/value pairs? I don't mind doing that but it seems odd and very 1998- am I missing something here? How are we supposed to parse cookies in an HttpRequestMessage in 4.6.1?

Thanks,

JB

Edit: reading a little further is seems CookieHeaderValue is part of .NET Core??

  

Error making a POST request with Bearer Token to REST API using C#

$
0
0

I am able to POST to an REST API with Basic authentication and getting  successful response back, along with the Token. Now I need to pass the token to the site. I am having some difficulties as to passing the Bearer Token. I get a Forbidden error. Can some please give some thoughts where am I missing something?

Thanks.

        String username = "username";
        String password = "pwd";
        string URL = "url/login";
        string URL2 = "url/sessions"
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = 0;

        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password)));
        using (var response = request.GetResponse())

        using (var reader = new StreamReader(response.GetResponseStream()))
        {

            string result = reader.ReadToEnd();
            txtResponse.Text = Convert.ToString(result);
        }

      using (var reader = new StreamReader(response.GetResponseStream()))
        {

            string result = reader.ReadToEnd();
            txtResponse.Text = Convert.ToString(result);
            JObject joResponse = JObject.Parse(result);
           apitoken = (string)joResponse["token"];

         }
//I get the correct token from above, but I get Forbidden error
        WebRequest request1 = HttpWebRequest.Create(URL2);
        request1.Headers.Add("Authorization", "Bearer " + apitoken);
        request1.Method = "POST";
        request1.ContentType = "application/json";
        var resp = request1.GetResponse();


Restful Web API not working (HTTP 404 Not Found)

$
0
0

Hi,

New to WebAPI Restful service. This is what I have done.

Tried different approaches like attribute routing etc to pass multiple parameters

1) Global.asax.cs (Application Start Event)

      void Application_Start(object sender, EventArgs e)

      {

                 RouteTable.Routes.MapHttpRoute(

                   name:"DefaultApi",

                  routeTemplate:"api/{controller}/{action}/{id}",

                 defaults:new { id = RouteParameter.Optional }

                );

         }

2)   Controller

        

publicclassAccountController : ApiController

{

public IEnumerable<AccountModel> Get(int pClientID, int pProgramID)

{

NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);

int clientID = Convert.ToInt32(nvc["ClientID"]);

int programID = Convert.ToInt32(nvc["ProgramID"]);

returnnew AccountData().GetAccounts(pClientID, pProgramID);

}

}

call web api:

http://localhost:52724/api/Account?ClientID=19&ProgramID=93

Error:

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

<div class="content-container">

Most likely causes:

  • The directory or file specified does not exist on the Web server.
  • The URL contains a typographical error.
  • A custom filter or module, such as URLScan, restricts access to the file.
</div>

Detailed Error Information:

<div id="details-left">
Module   IIS Web Core
Notification   MapRequestHandler
Handler   StaticFile
Error Code   0x80070002
</div> <div id="details-right">
Requested URL   http://localhost:52724/api/Account?ClientID=19&ProgramID=93
Physical Path   C:\Apps\WebApplication1\WebApplication1\api\Account
Logon Method   Anonymous
Logon User   Anonymous
Request Tracing Directory   C:\Users\xxxxx\Documents\IISExpress\TraceLogFiles\WEBAPPLICATION1(2)
</div>

PHP OAuth 2.0 authorization API and .NET Resource API

$
0
0
So we have a custom built PHP authorization Server that uses OAuth 2.0 bearer tokens and several resource APIs built in PHP. these are on different machines.

Now we want to develop .NET APIs also but use the same authorization tokens. How can we implement this?

Kind of like this but the auth server obviously isn’t in .NET.
http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/

401, Unauthorized, WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"

$
0
0

Hi -

I am calling my Web Api from a console app and always get the unauthorized error.

<div>string aadInstance = "https://login.windows.net/common/oauth2/authorize";</div> <div>            string ResourceId = ConfigurationManager.AppSettings["ResourceId"];</div> <div>            string tenantId = ConfigurationManager.AppSettings["TenantId"];</div><div>            string clientId = ConfigurationManager.AppSettings["ClientId"];</div> <div>            string url = ConfigurationManager.AppSettings["url"];</div> <div>            AuthenticationContext authenticationContext =</div> <div>              new AuthenticationContext(aadInstance);</div> <div> </div> <div>            var uri = new Uri("https://localhost");</div> <div> </div> <div>            var platformParams = new PlatformParameters(PromptBehavior.Auto);</div> <div> </div> <div>            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceId, clientId, uri,  platformParams);</div><div></div> <div> <div>string token = authenticationResult .AccessToken;</div> <div>            if (token != null)</div> <div>            {</div> <div> </div> <div>                HttpClient client = new HttpClient();</div> <div>                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);</div> <div> </div> <div>                var response = await client.GetAsync(new Uri(url));</div> <div> </div> <div>                string content = response.Content.ReadAsStringAsync().Result;</div> <div>                Console.WriteLine(content);</div> <div>            }</div></div> <div> </div> <div>Note sure what I am  doing wrong.</div> <div></div> <div>Please help !</div> <div></div> <div>Thanks, Shilpi</div>

Read XML with or without namespace using frombody in Web API 2

$
0
0

Hi All,

I am facing an issue to handle a XML with/without namespace . I am able to read XML with namespace file if I provide/use the [XMLRoot(namespace="xyz")] on respective class object.
But If I pass without namespace XML file , object get/read as null .

I am looking for solution where I should able to read the file with/without namespace with same code.

Example :

With Namespace:

<?xml version="1.0" encoding="UTF-8"?><ns6:Root xmlns:ns6="http://www.abc-xml.org/3" xmlns:udt="http://www.openapplications.org/oagis/9/unqualifieddatatypes/1.1" xmlns:oa="http://www.openapplications.org/oagis/9" releaseID="1.0"><oa:RootArea><oa:CreationDateTime>2018-05-17</oa:CreationDateTime></oa:RootArea></ns6:Root >

Without Namespace:

<?xml version="1.0" encoding="UTF-8"?><Root xmlns:ns6="http://www.abc-xml.org/3" xmlns:udt="http://www.openapplications.org/oagis/9/unqualifieddatatypes/1.1" xmlns:oa="http://www.openapplications.org/oagis/9" releaseID="1.0"><RootArea><CreationDateTime>2018-05-17<CreationDateTime></RootArea></Root >

Code:

   [HttpPost]
        [Produces("application/xml", "application/json")]
        [Consumes("application/xml", "application/json")]  
public IActionResult Post([FromBody]RootClass _root, [FromHeader]string Authorization)
        {
}

Thanks in advance

Netra S W

How to get data from two tables using web api

$
0
0

I want to get data from two tables using web api, but I'm receiving an error.

Here is my code:

public List<tblEmpTask> GettblEmpTasks()
{
var q = (from n in db.tblEmpTasks
join c in db.tblEmployees on n.intEmpCode equals c.intEmpCode

select new
{
n.strTaskName,
n.dtStart,
c.strEmployeeName,

}).ToList();
return q;
}

Here is the error that I'm receiving:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

and please note that I am using web api. Looking forward to solve this issue.

Viewing all 4850 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>