Error 405- Method Not allowed WCF file upload with MVC - asp.net-mvc-3

I have created an MVC website that uses a WCF web service for file uploads. (Using Asp.net developer server) at the moment.(I'm quite new to WCF)
The web service is configured to use a "POST" i.e [WebInvoke(Method = "POST"]
However, I keep getting Error 405 after numerous tries and time spent browsing the web.
I presume this might be something to do with settings in the web.config file.
I just need to be clear on the exact settings to enable this work.
Here's my service contract
[ServiceContract]
public interface IFileUpload
{
[WebInvoke(Method = "POST", UriTemplate = "FileUpload/{session}/{fileName}", BodyStyle = WebMessageBodyStyle.Wrapped)]
bool Upload(string session, string fileName, Stream stream);
}

Related

How to read ASP.NET_SessionId in Web API Controllers?

We have a legacy ASP.NET WebForms project that I am trying to modernize by using Web APIs instead of the traditional [WebMethod] statics on Code-Behind (because it is just so limited).
However, I wanted to be able to read the Session Cookie in the Web API as well. Before, I can read it in the Code-Behind by accessing the HttpContext.Current.Session["NAME_OF_COOKIE_HERE"] and then casting it to a Model - I don't know how to do this with Web APIs.
I'm using axios to talk to my Web API Controllers.
I've added the withCredentials: true to my axios config but how do I move forward from there? How exactly can you read the session cookie in Web API Controllers?
Here's a sample:
// Client for testing
axios.get(API_ENDPOINT_URL_HERE, {withCredentials: true}).then(res => res).catch(err => err);
// Web API Controller
[Route(API_ENDPOINT_URL_ACCESSIBLE_BY_THE_CLIENT_TESTING)]
[HttpGet]
public IHttpActionResult SOME_FUNCTION_NAME() {
var currentUser = // I don't know what to do from here on.
}
The answer is in this link: ASP.NET Web API session or something?
Specifically, adding the following in the Global.asax.cs
public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
You can read cookie just like any header property in httpRequestMessage by HttpRequestMessage.Headers .Please follow the link with proper implementation
WebAPI: Getting Headers, QueryString and Cookie Values
Also please note that if you expect a cookie in the Request then use "Cookie" header key and if you are making an rest api call and trying to find cookie in response then use "Set-Cookie"

WebRequest between ASP.NET MVC Webs on the same server always not authorized (401)

I have two Webs, one ASP.NET MVC Core 2 and one ASP.NET MVC 5 both with windows authentication on the same server (IIS). Each web works perfect also the windows authentication. Now I have the need to call actions in the core web from the MVC 5 web like this:
WebRequest request = WebRequest.Create(source);
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
MemoryStream dataStream = new MemoryStream();
response.GetResponseStream().CopyTo(dataStream);
the problem is that I always get the not authorized (401) error - if a call the action from the browser it works but not with WebRequest...
in ASP.NET MVC 5 I have set windows authentication and
in ASP.NET MVC Core have set windows authentication and all works except the call from WebRequest...
any ideas whats the Problem?
as a side node: if I set the credentials like this it works but I don't need a fix account but the current logged on user
request.Credentials = new NetworkCredential("user", "password", "domain");
robert

How can I create a login page in Xamarin.Forms?

How can I create a login page using Xamarin.Forms?
I'm debugging on Android device and
on the page I try to query the given username and password from an MSSQL database in MSSQL
and if the login be successful, the page will navigate to a new page, else will show authentication failed.
How can I do this in Xamarin.Forms?
(Xamarin LoginFlow Example linked at bottom of answer)
You would have multiple Xamarin.Forms pages and use a NavigationPage to push or pop them from the (lifecycle) stack.
Ref: https://developer.xamarin.com/api/type/Xamarin.Forms.NavigationPage/
Think of each Page a complete self-contained mini application. So the Login page might handle the getting the UserID/Password interactively from the user, performing a authorization check via a server via a Rest api that performs your SQL query. If login is successful it pushes a new Forms-based page on the NavigationPage stack. i.e.
SplashScreen -> LoginPage -> MainPagePage
LoginFlow Xamarin example
This sample demonstrates how to manipulate the navigation stack in order to only display the main page of the application once the user has successfully logged in.
For more information about the sample see Hierarchical Navigation.
What you need is the following functionalities:
Web APIs (Web Service for Login - Hosted on internet or local network - Connected with your MSSql Server)
A Login Screen in Xamarin.Forms Application (You can design it on your own or use the above mentioned demo)
On Login Screen's 'Login' button click, you need to call the Login Web Service from Xamarin.Forms application.
This requires networking (Internet Permission on Android Project, through Manifest.xml). You can use Microsoft.Net.Http for Web Service Calls.
(Look at this example http://www.c-sharpcorner.com/UploadFile/nirmal.hota/consuming-restful-web-service-in-xamarin-forms-project-using/ )
If your server responses with JSON and you need to parse JSON then you can use Json.Net (Newtonsoft.Json).
Note: What I am trying to tell you is that you need to use Web Services that are connected to the database and hosted on a server. From Xamarin.Forms application, you have to call this web-service with appropriate parameters. This requires networking, so you can use Microsoft.Net.Http (or there are other plugins also available). To get response from the Web Service, if it is in Json then you can use Newtonsoft.Json to parse Json.
There is a full example of an app with login page: xamarin-forms-samples/LoginDemo/ provided by Xamarin.
So lets say you have a LoginController on asp.net web api (if you don't know how to create an asp.net web api project etc. this is not the place to learn it:) )
[RoutePrefix("v1/login")]
public class LoginController : ApiController
{
[Route("")]
[HttpPost] //I'm using post!!!!!! you may use get etc.
public IHttpActionResult Login(UserLoginData request)
{
var userData = CheckFromDb(request);
return Json(userData);
}
}
It checks your request from db (UserLoginData is a simple class lets say holds username and password), than if user exists you return another class (lets say it is UserData hat holds name,surname, birthday etc.). If it can not find login it may return null. It's up to you.
So it will be available on your host machine like
localhost:34252/v1/login
(34252 your port-may change for you)
So you have to call it from the device (xamarin.forms) code like this
public string Post(string url, UserLoginData userLoginData)
{
//url is login url as defined above and userLoginData holds your
//user interface (textbox) data :)
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, 30);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content;
content = new StringContent(JsonConvert.SerializeObject(userLoginData), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("call failed");
}
//this is your response as json
var responseString = response.Content.ReadAsStringAsync().Result;
//you can convert it and check to a specific class if you need
var userData = JsonConvert.DeserializeObject<UserData>(responseString);
}
}
So UserLoginData and UserData classes both must exists on both sides. You can use Newtonsoft.Json library for json parsing (jsonconvert is it's method). Hope this helps you
And android device simulator networking is a bit tricky. You may not connect to localhost directy. It may take an address like 10.0.2.* for androidemulator or 10.71.34.* for xamarin simulator. Please check your network cards for ip addresses and findthe correct one via "cmd.exe" and "ipconfig /all" command.

OAUth2 ASP.NET invalid_grant

I am trying to implement OAUTH2 for my web application but even though signing in to the application works, refresh tokens result in an HTTP 400 "invalid_grant".
Specifically, the project is an ASP.NET WebAPI with OWIN OAuth provider. This has been killing me for days without luck so any help will be appreciated :)
Have you correctly set OAuthAuthorizationServerOptions.RefreshTokenProvider?
If you need a sample, Katana's sandbox project contains a minimal implementation showing how you can easily configure it to protect and serialize refresh tokens using the data protection block (machine keys on IIS): https://github.com/jchannon/katanaproject/blob/master/tests/Katana.Sandbox.WebServer/Startup.cs#L169-L173
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions {
RefreshTokenProvider = new AuthenticationTokenProvider {
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
}
});
private void CreateRefreshToken(AuthenticationTokenCreateContext context) {
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context) {
context.DeserializeTicket(context.Token);
}
If it still doesn't work, try enabling tracing to determine the root cause of the invalid_grant error: http://katanaproject.codeplex.com/wikipage?title=Debugging&referringTitle=Documentation
We were getting the same issue when deploying the AuthorizationServer on Azure and trying to access it through localhost.
Later we deployed all 3:
AuthorizationServer
AuthrizationCodeGrant
Resource Server
Made required changes in the Constants\Paths.cs for the deployed URLs.
Even after this it did not work. But once we changed all the paths to HTTPS it all started working smoothly.
Please try that in case you are still stuck.

multiple self-hosted webapi on same server

I want to host, mutiple self-hosted webapi's along with the web-site on the same machine / windows 2k8 server. For hosting the website I am using IIS. and for webapi's I would be using self-hosted webapi 2. How do I configure using self-hosted webapi, so that everything can work in sync on same server.
So lets say I will host the website at http://example.com/mysite and I will be hosting the webapi at http://example.com/apiws and http://example.com/apiui
I am using windows service for the configuration. This is how the web-api self hosting looks like as of now - for first webapi.
protected override void OnStart(string[] args)
{
_config = new HttpSelfHostConfiguration(ServiceAddress);
_config.MapHttpAttributeRoutes();
_config.Routes.MapHttpRoute("DefaultApi",
"apiws/{controller}/{id}",
new { id = RouteParameter.Optional });
_server = new HttpSelfHostServer(_config);
_server.OpenAsync().Wait();
}
the configuration is almost same for the second server as well.
My question is having all of them working on the same port, is it possible? are there any issues which might arise? etc?
you are confusing web-api with mvc.
MVC/IIS/websites needs hosting on domain on sub-domain.
webapi are just for listening to the request and providing the data response.

Resources